package com.dq.controller.api.staff;

import com.dq.domain.sys.user.center.UserAccountStaffUser;
import com.dq.exception.customException.AdminException;
import com.dq.exception.customException.ApiException;
import com.dq.controller.in.query.GoodsQuery;
import com.dq.controller.in.query.SaleHistoryOrderQuery;
import com.dq.controller.in.request.OrderRequest;
import com.dq.controller.in.request.TakeItInStaffCartRequest;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.vo.ListVo;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.goods.Product;
import com.dq.domain.goods.ShoppingBag;
import com.dq.domain.orders.Orders;
import com.dq.domain.org.Org;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.domain.sys.user.user.WxUser;
import com.dq.service.AllService;
import com.dq.utils.ListUtils;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author luchangtong
 * @Date 2019/12/3 9:24
 */
@Api(description = "技师 销售单")
@RestController
@RequestMapping("/staff/order")
public class StaffUserOrderController extends AllService {
    @Value("${express_time}")
    protected Long expressTime;
    @ApiOperation("员工下单")
    @PostMapping("submitStaffOrder")
    public Vo submitStaffOrder (@RequestBody @Valid TakeItInStaffCartRequest takeItInCartRequest) throws AdminException, ApiException {
        SysUser user = sysUserService.getUser();
        Org org = (Org) user.getSection();
        if (null == org || org.getId() == null) {
            throw new ApiException("用户所属门店信息异常");
        }
        List<ShoppingBag> bags = shoppingBagService.findByIdIn(takeItInCartRequest.getBagIds());
        if (null == bags || bags.isEmpty()) {
            throw new ApiException("购物车不能为空");
        }
        for (ShoppingBag bag: bags ) {
            if(goodsService.productStock(bag.getProduct().getId(),user.getSection().getId()) - bag.getNumber() < 0){
                throw new AdminException("库存不足");
            }
        }
        // 关联员工
        List<Long> staffUserIds = takeItInCartRequest.getStaffUserIds();
        if(staffUserIds == null) {
            staffUserIds = new ArrayList<>();
        }
        if(staffUserIds.isEmpty()) {
            staffUserIds.add(user.getId());
        }else {
            if(ListUtils.listIn(user.getId(), staffUserIds) == -1) {
                staffUserIds.add(user.getId());
            }
        }
        ordersService.takeItInStaffUserCart(bags, org, takeItInCartRequest.getNote(),expressTime, staffUserIds,takeItInCartRequest.getGiveProject(),takeItInCartRequest.getGiveIntegral(),takeItInCartRequest.getWxUserId(),takeItInCartRequest.getFlag(),takeItInCartRequest.getArrearPrice(),takeItInCartRequest.getDiscountPrice());
        return new Vo(HttpStatus.OK);
    }
    //根据name查用户

    @ApiOperation("根据用户姓名查")
    @GetMapping("getInfo/{userRealCName}")
    public Vo getInfo(@PathVariable @ApiParam("姓名")String userRealCName) throws AdminException {
        List<WxUser> list= wxUserRepository.findByUserRealcNameAndDeletedFalse(userRealCName);
        List<WxUser.SimpleWxUser> wxUserList = new ArrayList<>();
        if(list.size() == 0){
            throw new AdminException("无此用户");
        }
        list.forEach(wxUser -> {
            wxUserList.add(wxUser.toSimpleWxUser(wxUser.getSection().getSimpleName()));
        });
        return new Vo(wxUserList);
    }

    @ApiOperation("根据用户姓名模糊查")
    @GetMapping("getLikeInfo/{userRealCName}")
    public Vo getLikeInfo(@PathVariable @ApiParam("姓名")String userRealCName) throws AdminException {
        List<WxUser> list= wxUserRepository.findByUserRealcNameLikeAndDeletedFalse(BaseAdminQuery.likeSql(userRealCName));
        List<WxUser.SimpleWxUser> wxUserList = new ArrayList<>();
        if(list.size() == 0){
            throw new AdminException("无此用户");
        }
        list.forEach(wxUser -> {
            wxUserList.add(wxUser.toSimpleWxUser(wxUser.getSection().getSimpleName()));
        });
        return new Vo(wxUserList);
    }

    @ApiOperation("根据用户工号查")
    @GetMapping("getInfoByCardNo/{cardNo}")
    public Vo getInfoByCardNo(@PathVariable @ApiParam("工号")String cardNo) throws AdminException {
        List<StaffUser> list= staffUserRepository.findByCardNoAndDeletedFalse(cardNo);
        List<StaffUser.SimpleWxUser> wxUserList = new ArrayList<>();
        if(list.size() == 0){
            throw new AdminException("无此用户");
        }
        list.forEach(staffUser -> {
            wxUserList.add(staffUser.toSimpleWxUser());
        });
        return new Vo(wxUserList);
    }


    @ApiOperation("技师销售历史订单")
    @PostMapping("saleHistoryOrderList")
    public Vo saleHistoryOrderList(@RequestBody SaleHistoryOrderQuery saleHistoryOrderQuery) throws AdminException {
        if(saleHistoryOrderQuery.getStaffUserId() == null){
            throw new AdminException("参数不能为空");
        }
        saleHistoryOrderQuery.format();
        Map<String, Object> query = saleHistoryOrderQuery.parseMap();
        if(saleHistoryOrderQuery.getStaffUserId()!=null){
            query.put("staffUser_id",saleHistoryOrderQuery.getStaffUserId());
            query.remove("staffUserId");
        }
        if(StringUtils.isNotEmpty(saleHistoryOrderQuery.getWxUserName())){
            query.put("userOrder_wxUser_userRealcName"+ BaseDaoImpl.likeSqlStr,"%"+saleHistoryOrderQuery.getWxUserName()+"%");
            query.remove("wxUserName");
        }
        if(saleHistoryOrderQuery.getBeginTime() != null){
            query.put("createTime"+ BaseDaoImpl.gteSqlStr,saleHistoryOrderQuery.getBeginTime());
            query.remove("beginTime");
        }
        if(saleHistoryOrderQuery.getEndTime() != null){
            query.put("createTime"+ BaseDaoImpl.lteSqlStr,saleHistoryOrderQuery.getEndTime());
            query.remove("endTime");
        }
        List<UserAccountStaffUser> list = dao.find(dao.query2Hql(UserAccountStaffUser.class, query), query);
        Long count = dao.count(dao.count2Hql(UserAccountStaffUser.class, query), query);
        List<UserAccountStaffUser.StaffOrderListVo> listVos = new ArrayList<>();
        list.forEach(userOrderStaffUser -> {
            listVos.add(userOrderStaffUser.toStaffOrderListVo());
        });
        PageInfo pageInfo = new PageInfo(listVos);
        pageInfo.setTotal(count);
        return new Vo(pageInfo);
    }

    @PostMapping("/list")
    @ApiOperation("模糊多条件检索门店商品列表")
    public ListVo productList(@RequestBody GoodsQuery goodsQuery) throws AdminException, ApiException {
        goodsQuery.format();
        Map<String, Object> query = goodsQuery.parseMap();
        //保存热词入库
        if (StringUtils.isNotBlank(goodsQuery.getGoodsName())) {
            query.put("goods_goodsName"+ BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(goodsQuery.getGoodsName()));
            query.remove("goodsName");
        }
        if (goodsQuery.getCategoryId() != null) {
            query.put("goods_category_id", goodsQuery.getCategoryId());
            query.remove("categoryId");
        }
        if(goodsQuery.getIsRecommend() != null){
            query.put("goods_isRecommend",goodsQuery.getIsRecommend());
            query.remove("isRecommend");
        }
        if(goodsQuery.getPriceMin() != null){
            query.put("goods_price"+ BaseDaoImpl.gteSqlStr,goodsQuery.getPriceMin());
            query.remove("priceMin");
        }
        if(goodsQuery.getPriceMin() != null){
            query.put("goods_price"+ BaseDaoImpl.lteSqlStr,goodsQuery.getPriceMax());
            query.remove("priceMax");
        }
        if(goodsQuery.getGoodsStatus()!= null){
            query.put("goods_goodsStatus", goodsQuery.getGoodsStatus());
            query.remove("goodsStatus");
        }
        if(goodsQuery.getStatus() != null){
            query.put("goods_showStatus", goodsQuery.getStatus());
            query.remove("status");
        }
        query.put("goods_isIntegralGoods",false);
        List<Product> goodsList = dao.find(dao.query2Hql(Product.class, query), query);
        Long count = dao.count(dao.count2Hql(Product.class, query), query);
        return new ListVo((List<Product.Vo>) VO.toVOCollection(goodsList), count);
    }


    @PostMapping("/selectProject")
    @ApiOperation("线下下单选择服务项目和次数")
    public Vo selectProject(@RequestBody OrderRequest request) throws AdminException{
        Orders orders = dao.get(Orders.class,request.getId());
        orders.setServiceProject(request.getServiceProject());
        return new Vo();
    }
}
